<?php
/**
 * Created by yb.
 * Author: 1021948372@qq.com
 * Date: 2020/7/7 07:07
 */
namespace app\admin\controller;
use app\common\lib\SessionCheck;
use think\Db;
use think\facade\Request;

class Files extends SessionCheck
{
    protected $template_path;
    function initialize()
    {
        parent::initialize();
        $this->template_path = 'uploads/';
    }

    //媒体文件
    public function index(){
        $path = $this->template_path . Request::param('folder');
        $folder = Request::param('folder') ? Request::param('folder') : '';
        $this->view->assign('folder',$folder);

        $uppath = explode('/',Request::param('folder'));
        $leve = count($uppath)-1;
        unset($uppath[$leve]);
        if($leve>1){
            unset($uppath[$leve-1]);
            $uppath = implode('/',$uppath).'/';
        }else{
            $uppath = '';
        }
        $this->view->assign('leve',$leve);
        $this->view->assign('uppath',$uppath);

        $files = glob($path.'*');
        $folders = $templates = array();
        foreach($files as $key => $file) {
            $filename = basename($file);
            if(is_dir($file)){
                $folders[$key]['filename'] = $filename;
                $folders[$key]['filepath'] = $file;
                $folders[$key]['ext'] = 'folder';
            }else{
                $templates[$key]['filename'] = $filename;
                $templates[$key]['filepath'] = '/' . ltrim($file,'.') ;
                $templates[$key]['ext'] = strtolower(substr($filename,strrpos($filename, '.')-strlen($filename)+1));
                if(!in_array($templates[$key]['ext'],array('gif','jpg','png','bmp'))) $templates[$key]['ico'] =1;
            }
        }
        $this->view->assign('folders',$folders );         //文件夹
        $this->view->assign('files',$templates );         //文件
        return $this->view->fetch();
    }

    //媒体文件删除
    public function del(){
        $folder = str_replace("..", "", Request::post('folder'));
        $path = $this->template_path . $folder;
        $file = $path . $this->checkFilename(Request::post('filename'));

        if(file_exists($file)){
            is_dir($file) ? dir_delete($file) : unlink($file);
            $this->success('删除成功！');
        }else{
            $this->error('删除失败');
        }
    }

    //过滤文件名
    private function checkFilename($fileName)
    {
        $fileName = str_replace("/", "", $fileName);
        $fileName = str_replace("..", "", $fileName);
        $fileName = str_ireplace(".php", ".html", $fileName);
        return $fileName;
    }
}
